import { useQuery } from "@tanstack/react-query";
import { useCookies } from "react-cookie";
import { useMemo } from "react";
import { TOKEN } from "@/constants/cookies";
import { isUrl } from "@/lib/utils";

/**
 * useAvatar hook for fetching user avatar image
 */
export const useAvatar = (imageId?: string | null) => {
  const [cookies] = useCookies([TOKEN]);

  const query = useQuery({
    queryKey: ["avatar", imageId],
    queryFn: async (): Promise<string | null> => {
      if (!imageId) {
        return null;
      }

      // 如果 imageId 是 URL，直接返回
      if (isUrl(imageId)) {
        return imageId;
      }

      const token = cookies.access_token;
      if (!token) {
        return null;
      }

      // 直接返回图片的 URL，而不是创建 blob URL
      return `/api/file/image/${imageId}`;
    },
    staleTime: 30 * 60 * 1000, // 30分钟
    gcTime: 60 * 60 * 1000, // 60分钟
    enabled: !!imageId && !!cookies.access_token,
  });

  const avatarUrl = useMemo(() => {
    if (query.data) {
      return query.data;
    }
    return null;
  }, [query.data]);

  return {
    avatarUrl,
    loading: query.isLoading,
    error: query.error,
    refetch: query.refetch,
    cleanup: () => {}, // 空函数，因为不再需要清理 blob URL
  };
};
